﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using vJine.Core.IoC;

namespace vJine.Core.Log {
    public class Profiler {
        Stopwatch watch = null;
        StringBuilder Info = new StringBuilder();
        public Profiler() {
            this.watch = new Stopwatch();
            this.watch.Start();
        }

        public void Tag() {
            this.Tag(null);
        }

        public void Tag(string tag) {
            if (this.Info.Length > 0) {
                this.Info.Append(",");
            }

            if (string.IsNullOrEmpty(tag)) {
                this.Info.Append(tag).Append(",");
            }
            this.Info.Append(this.watch.ElapsedMilliseconds);
        }

        public override string ToString() {
            this.Tag("#total");
            return this.Info.ToString() + "\r\n";
        }

        public static double Profile(int times, Exec worker) {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < times; i++) {
                worker();
            }
            watch.Stop();

            return watch.ElapsedMilliseconds;
        }

        public static double Profile<T>(Exec<T> worker, int times, T arg) {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < times; i++) {
                worker(arg);
            }
            watch.Stop();

            return watch.ElapsedMilliseconds;
        }

        public static double Profile<T>(Exec<T> worker_1, Exec<T> worker_2, int times, T arg) {
            double time_takes_1 = Profiler.Profile<T>(worker_1, times, arg);
            double time_takes_2 = Profiler.Profile<T>(worker_2, times, arg);
            if (time_takes_2 == 0) {
                return double.PositiveInfinity;
            } else {
                return time_takes_1 / time_takes_2;
            }
        }
    }
}
